package com.ryan.ohos.extension.util;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * ThreadPoolManager
 *
 * @author wangyin
 * @since 2021/07/21
 */
public class ThreadPoolManager {

    /**
     * threadPoolManager
     */
    private volatile static ThreadPoolManager threadPoolManager = null;

    /**
     * ExecutorService
     */
    private volatile ExecutorService executor;

    /**
     * monitor1
     */
    private static final Object MONITOR_1 = new Object();

    /**
     * monitor2
     */
    private static final Object MONITOR_2 = new Object();

    /**
     * ThreadPoolManager.getInstance
     *
     * @return ThreadPoolManager
     */
    public static ThreadPoolManager getInstance() {
        if (threadPoolManager == null) {
            synchronized (MONITOR_1) {
                if (threadPoolManager == null) {
                    threadPoolManager = new ThreadPoolManager();
                }
            }
        }
        return threadPoolManager;
    }

    /**
     * getExecutor
     *
     * @return ExecutorService
     */
    public ExecutorService getExecutor() {
        if (executor == null) {
            synchronized (MONITOR_2) {
                if (executor == null) {
                    executor = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                            60L, TimeUnit.SECONDS,
                            new SynchronousQueue<>());
                }
            }
        }
        return executor;
    }

    /**
     * ThreadPoolManager
     */
    private ThreadPoolManager() {
    }

    /**
     * 执行 runnable
     *
     * @param runnable runnable
     */
    public void execute(Runnable runnable) {
        getExecutor().execute(runnable);
    }

    /**
     * shutDown
     * 关闭线程
     */
    public void shutDown() {
        getExecutor().shutdown();
    }

    /**
     * shutDownNow
     * 尝试停止所有正在执行的任务，停止正在等待的任务的处理，并返回正在等待执行的任务的列表
     * @return List<Runnable>
     */
    public List<Runnable> shutDownNow() {
        return getExecutor().shutdownNow();
    }
}
